<template>
  <div class="center">
    <el-form ref="form" :model="form" label-width="100px" :rules="rules" >
      <el-form-item label="头像:" label-width="120px" prop="avatar">
        <el-upload class="avatar-uploader" action :auto-upload="false" :show-file-list="false" :before-upload="beforeAvatarUpload" :on-change="imgUpload">
          <img v-if="form.avatar" :src="form.avatar" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <div class="flex">
        <el-form-item label="账号:" prop="username" >
          <el-input v-model="form.username" :disabled="this.isEdit"></el-input>
        </el-form-item>
        <el-form-item label="昵称:">
          <el-input v-model="form.nickname"></el-input>
        </el-form-item>

        <el-form-item label="真实姓名:">
          <el-input v-model="form.realName"></el-input>
        </el-form-item>
      </div>
      <div class="flex">
        <el-form-item label="毕业院校:">
          <el-input v-model="form.school"></el-input>
        </el-form-item>
        <el-form-item label="专业:">
          <el-input v-model="form.major"></el-input>
        </el-form-item>
        <el-form-item label="所在城市:">
          <el-input v-model="form.city"></el-input>
        </el-form-item>
      </div>
      <div class="flex">
        <el-form-item label="密码:" prop="password">
          <el-input placeholder="密码需为6位字母或数字" v-model="form.password"  >
            <el-button slot="append" icon="el-icon-refresh-left" type="primary" @click="randomPassword"> 随机密码</el-button>
          </el-input>
        </el-form-item>
      </div>

      <el-form-item label="类别:" prop="teachType">
        <el-select v-model="form.teachType" placeholder="请选择教师类别" :disabled="$route.query.teach_type !== undefined">
          <el-option label="教师" :value="1"></el-option>
          <el-option label="观察员" :value="4"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="性别:">
        <el-select v-model="form.gender" placeholder="请选择性别">
          <el-option label="男" :value="1"></el-option>
          <el-option label="女" :value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学历:">
        <el-select v-model="form.education" placeholder="请选择学历">
          <el-option label="高中" :value="1"></el-option>
          <el-option label="中等专科" :value="2"></el-option>
          <el-option label="大学专科" :value="3"></el-option>
          <el-option label="大学本科" :value="4"></el-option>
          <el-option label="硕士研究生" :value="5"></el-option>
          <el-option label="博士研究生" :value="6"></el-option>
          <el-option label="博士后" :value="7"></el-option>
        </el-select>
      </el-form-item>
      <div class="flex">
        <el-form-item label="出生日期:">
          <el-date-picker type="date" placeholder="选择日期" :picker-options="pickerOptions" :default-value="defaultTime" v-model="form.birthday" style="width: 100%;" value-format="timestamp"></el-date-picker>
        </el-form-item>
      </div>
      <div class="flex">
        <el-form-item label="手机号码:" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机号码"></el-input>
        </el-form-item>
      </div>

      <div class="flex">
        <el-col :span="4">
          <el-form-item label="教师资格证:">
            <el-radio-group v-model="form.teacherCert">
              <el-radio :label="1">有</el-radio>
              <el-radio :label="-1">无</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-form-item label="擅长学科:">
          <el-input v-model="form.subject"></el-input>
        </el-form-item>
      </div>

      <div class="flex">
        <el-form-item label="督学经验值:">
          <el-input type="number" v-model="form.sub_exp" :min="0"></el-input>
        </el-form-item>
        <el-form-item label="伴学经验值:">
          <el-input type="number" v-model="form.acc_exp" :min="0"></el-input>
        </el-form-item>
        <el-form-item label="点赞值:">
          <el-input type="number" v-model="form.like_value" :min="0"></el-input>
        </el-form-item>
      </div>
      <el-form-item label="教师简介:">
        <el-input type="textarea" v-model="form.desc" maxlength="350" :autosize="{minRows:2, maxRows:10}"></el-input>
      </el-form-item>
      <el-form-item label="远控学生屏幕功能:" label-width="150px">
        <div class="flex">
          <div class="mr-5">开通后可对名下任何学生进行屏幕远控操作（3500元/年)</div>
          <el-button :disabled="!isEdit" @click="toWxPrePay(3500)">点击开通</el-button>
        </div>
      </el-form-item>
      <el-form-item label="音视频语音时长储值:" label-width="150px">
        <div>可与名下任何单个或多个学生进行音视频聊天(注:1对N，则会按N*时长进行核算;时长有效期为12个月)</div>
        <div>
          <el-button :disabled="!isEdit" @click="toWxPrePay(5)">储值100分钟  5元</el-button>
          <el-button :disabled="!isEdit" @click="toWxPrePay(15)">储值500分钟  15元</el-button>
          <el-button :disabled="!isEdit" @click="toWxPrePay(25)">储值1000分钟  25元</el-button>
          <el-button :disabled="!isEdit" @click="toWxPrePay(75)">储值3000分钟  75元</el-button>
          <el-button :disabled="!isEdit" @click="toWxPrePay(115)">储值5000分钟  115元</el-button>
        </div>
      </el-form-item>
      <el-form-item>
        <div style="display: flex; justify-content: center">
          <el-button v-if="isEdit" type="primary" @click="editSubmit">立即修改</el-button>
          <el-button v-else type="primary" @click="onSubmit">立即创建</el-button>
          <el-button @click="goBack">取消</el-button>
        </div>
      </el-form-item>
    </el-form>
    <el-dialog title="支付" :visible.sync="payVisible" width="30%" :before-close="closePayInfo">
      <div class="qrcode_box">
        <canvas id="canvas" ref="qrcodeCanvas" class="qrcode"></canvas>
        <div style="color: #409EFF">请使用微信支付</div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addTeacher, editTeacher, getTeacherById, wxPayInfo} from "@/api/teacher";
import {ossImage} from "@/utils/ossUpload";
import QRCode from "qrcode";
import {wxTransactions} from "@/api/wxAccounts";

export default {
  name: "add",
  data() {
    return {
      form: {
        username: '',
        nickname: '',
        teachType: this.$route.query.teach_type,  //1:督学师 2:伴学师 3:双师资格 4.观察员
        password: '',
        realName: '',
        mobile: '',
        gender: '', //性别 1：男 0：女
        birthday: '',
        city: '',
        school: '',  //毕业院校
        major: '',
        education: '', //学历
        teacherCert: -1,  //教师资格证 1：有 -1：无
        desc: '',
        subject: '',
        sub_exp: 500, //督学经验值
        acc_exp: 500, //伴学经验值
        like_value: 100, //点赞值
        avatar: '',
      },
      isEdit: Boolean(this.$route.query.isEdit),
      id: this.$route.query.id,
      agentId: this.$route.query.agentId,
      rules: {
        username: [{required: true, message: '请输入账号名', trigger: 'blur'}],
        teachType: [{required: true, message: '请选择教师类别', trigger: 'change'}],
        password: [{required: true, message: '请输入密码', trigger: 'blur'},{min:6,max:6, message: '长度需为6位'}],
        mobile: [{required: true, message:'请输入手机号码', trigger: 'blur'}]
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e6
        }
      },
      defaultTime: new Date('2000-01-01'),
      payVisible: false,
      codeUrl: '',
      outTradeNo: '',
      intervalId: null,
    }

  },
  created() {
    const query = this.$route.query
    this.isEdit = Boolean(Number(query.isEdit))
    this.form.teachType = Number(query.teach_type);
    this.agentId = query.agentId
   if (this.isEdit) {
     this.getTeacher(this.id)
   }
  },
  destroyed() {
    this.stopPolling()
  },
  beforeDestroy() {
    this.stopPolling()
  },
  methods: {
    onSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.form))
          addForm.last_ip = sessionStorage.getItem("Ip")
          addForm.userId = localStorage.getItem("ID")
          addForm.agentId = this.agentId
          addTeacher(addForm).then(res => {
            this.$message.success(res.msg)
            this.$router.back()
          }).catch(err => {
            this.$message.error("添加失败")
          })

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    editSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let editForm = JSON.parse(JSON.stringify(this.form))
          editForm.last_ip = sessionStorage.getItem("Ip")
          editForm.userId = localStorage.getItem("ID")
          editTeacher(editForm).then(res => {
            this.$message.success(res.msg)
            this.$router.back()
          }).catch(err => {
            this.$message.error("编辑失败")
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    getTeacher(id) {
      getTeacherById({id:id}).then(res => {
        this.form = res.data
      }).catch(err => {})
    },
    toWxPrePay(total) {
      wxPayInfo({
        userId: localStorage.getItem("ID"),
        teacherId: this.id,
        last_ip: localStorage.getItem("Ip"),
        total: total

      }).then(res => {
        this.codeUrl = res.data['code_url']
        this.outTradeNo = res.data['out_trade_no']
        this.payVisible = true
        this.$nextTick(() => {
          const canvas = document.getElementById('canvas')
          console.log("这是收到的coderUrl", this.codeUrl)
          var text = this.codeUrl
          const ctx = canvas.getContext('2d')
          QRCode.toCanvas(canvas, text, error => {
            if (error) console.log(error)
          })
          this.startPolling()
        })
      })
    },
    startPolling() {
      this.intervalId = setInterval(this.interPaymentWx, 2000); //每两秒更新一次
    },
    stopPolling() {
      if (this.intervalId) clearInterval(this.intervalId)
    },
    closePayInfo() {
      this.stopPolling()
      this.payVisible = false
    },
    //查询订单状态
    interPaymentWx() {
      wxTransactions({
        out_trade_no: this.outTradeNo
      }).then(res => {
        let trade_state = res.data['trade_state']
        if (trade_state === 'SUCCESS') {
          this.$message({
            message: '支付成功',
            type: 'success'
          })
         this.payVisible = false
          this.stopPolling()
        }
      })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    //图片上传
    imgUpload(res, file) {
      ossImage(res.raw,res.name).then(res => {//图片上传
        this.form.avatar = res
      }).catch(err => {
        this.$message.error("图标上传失败")
      })
    },
    randomPassword() {
      // 可选字符集，包括大写字母、小写字母和数字
      var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      // 创建一个长度为6的字符串
      var result = '';
      for (var i = 0; i < 6; i++) {
        // 随机选择字符集中的一个字符
        result += characters.charAt(Math.floor(Math.random() * characters.length));
      }
      this.form.password = result
    },
    goBack() {
      this.$router.back()
    }

  }
}
</script>


<style scoped lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.qrcode_box {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  width: 100%;

  .qrcode {
    width: 270px !important;
    height: 270px !important;
  }
}
</style>
